package edu.ynu.se.xiecheng.achitectureclass.GreenHouse.utils;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import java.io.FileOutputStream;
import java.io.IOException;

public class ImageDownloader {

    private OkHttpClient client = new OkHttpClient();

    /**
     * 下载图片并保存到本地
     *
     * @param picUrl       图片的 URL
     * @param localFilePath 本地保存路径
     * @throws IOException 如果下载或保存失败
     */
    public void downloadImage(String picUrl, String localFilePath) throws IOException {
        Request request = new Request.Builder()
                .url(picUrl)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Failed to fetch image from URL: " + picUrl + ", code: " + response.code());
            }

            ResponseBody body = response.body();
            if (body == null) {
                throw new IOException("Response body is null");
            }

            // 保存图片到本地
            try (FileOutputStream fos = new FileOutputStream(localFilePath)) {
                fos.write(body.bytes());
            }
        } catch (Exception e) {
            throw new IOException("Failed to download or save image: " + e.getMessage(), e);
        }
    }
}